﻿/*
 * Crée par SharpDevelop.
 * Utilisateur: eldunkerquois
 * Date: 27/06/2011
 * Heure: 15:35
 * 
 * Pour changer ce modèle utiliser Outils | Options | Codage | Editer les en-têtes standards.
 */
using System;
using System.Web;
using Db4objects.Db4o;
using Db4objects.Db4o.CS;

using System.Configuration;

namespace Db4oDoc.WebApp.Infrastructure
{
	/// <summary>
	/// Db4oProvider. Module gérant l'ouverture fermeture des connections Db4o
	/// </summary>
	public class Db4oProvider:IHttpModule
	{
		private const String DataBaseInstance = "openxmlbutter" ;
		private const String SessionKey = "DbSessionKey" ;
		public Db4oProvider()
		{
		}
		
		public void Init(HttpApplication context)
		{
			Console.WriteLine("Init");
			if (null == HttpContext.Current.Application[DataBaseInstance])
			{
				HttpContext.Current.Application[DataBaseInstance] = OpenDatabase();
				Console.WriteLine("db en session" ) ;
			}
			RegisterSessionCreation(context);
		}

		private IEmbeddedObjectContainer OpenDatabase()
		{
			string relativePath = ConfigurationManager.AppSettings["DatabaseFileName"];
			string filePath = relativePath;//HttpContext.Current.Server.MapPath(relativePath);
			Console.WriteLine("Ouverture de la base ..." );
			return Db4oEmbedded.OpenFile(filePath);

			
		}
		
		public void Dispose()
		{
			IDisposable toDispose = HttpContext.Current.Application[DataBaseInstance] as IDisposable;
			if (null != toDispose)
			{
				toDispose.Dispose();
			}
			Console.WriteLine("Dispose") ;
		}
		
		private void RegisterSessionCreation(HttpApplication httpApplication)
		{
			httpApplication.BeginRequest += OpenSession;
			httpApplication.EndRequest += CloseSession;
		}

		private void OpenSession(object sender, EventArgs e)
		{
			try
			{
				Console.WriteLine("debut open session");
				IEmbeddedObjectContainer container =
					(IEmbeddedObjectContainer)HttpContext.Current.Application[DataBaseInstance];
				Console.WriteLine("juste avant open");
				IObjectContainer session = container.Ext().OpenSession();
				HttpContext.Current.Items[SessionKey] = session;
				Console.WriteLine("fin open session");
				
//				Console.WriteLine("Ouverture connection pour la session" );
//				IEmbeddedObjectContainer server = (IEmbeddedObjectContainer)HttpContext.Current.Application[DataBaseInstance];
//				Console.WriteLine("recup container " + (server.Ext().IsClosed()) );
//
//				IObjectContainer session = server.Ext().OpenSession() ;
//				Console.WriteLine("Ouvrir une session db4o" ) ;
//				HttpContext.Current.Items[SessionKey] = session;
//				Console.WriteLine("Ouverture connection ok" );
			}
			catch (Exception exc )
			{
				Console.WriteLine("pb dans le open " + exc.Message );
			}
		}

		private void CloseSession(object sender, EventArgs e)
		{
			try
			{
				Console.WriteLine("fermeture connection pour la session..." );
				IObjectContainer session = (IObjectContainer)HttpContext.Current.Items[SessionKey];
				//session.Close();
				Console.WriteLine("OK bad " + (session!= null) ) ;
				session.Dispose();
				Console.WriteLine("fermeture connection pour la session" );
			}
			catch( Db4objects.Db4o.Ext.CompositeDb4oException cp )
			{
				Console.WriteLine("erreur composite !" );
				foreach ( Exception exp in cp._exceptions)
				{
					Console.WriteLine( exp.Message ) ;
				}
			}
			catch (Exception ec )
			{
				Console.WriteLine("pb dans la fermeture " +ec.Message );
			}
			
		}

		public static IEmbeddedObjectContainer Database
		{
			get { return (IEmbeddedObjectContainer)HttpContext.Current.Items[SessionKey]; }
		}

	}
}
